#include "Image.h"

#include "_Image.h"
#include "_Luly.h"

static _Image& image = _Image::getInstance();
Image::Image(std::string fileName, std::string imageId) : imageId(imageId) {
  image.loadImage(fileName, imageId);
}

Image::Image(std::string imageId) {
  if (image.hasImage(imageId)) {
    Image::imageId = imageId;
  } else {
    SDL_LogError(0, "不存在该图片，id:%s", imageId.c_str());
    // throw ;
  }
}

int Image::getWidth() { return image.getImageSurface(imageId)->w; }

int Image::getHeight() { return image.getImageSurface(imageId)->h; }

//原图绘制，只绘制一帧
void Image::draw(int x, int y) { image.draw(imageId, x, y); }

//缩放，旋转绘制，只绘制一帧
void Image::draw(int x, int y, double scale, double angle) {
  image.draw(imageId, x, y, scale, angle);
}

//只绘制某部分
void Image::draw(Rect cut, int x, int y, double destWidth, double destHeight,
                 double angle) {
  SDL_Rect sCut = {cut.x, cut.y, cut.width, cut.height};
  image.draw(imageId, sCut, x, y, destWidth, destHeight, angle);
}


void Image::drawArea(Rect area, Rect cut, Rect dest, double angle) {
  // void Image::drawArea(Rect area, Rect cut, int destx, int desty,
  //                      double destWidth, double destHeight, double angle) {
  int relativeX = area.x - dest.x;
  relativeX = (relativeX < 0) ? 0 : relativeX;
  int relativeY = area.y - dest.y;
  relativeY = (relativeY < 0) ? 0 : relativeY;
  int destw = overlap(dest.x, dest.x + dest.width, area.x, area.x + area.width);
  int desth =
      overlap(dest.y, dest.y + dest.height, area.y, area.y + area.height);
  int srcx = (int)((relativeX / (float)dest.width) * cut.width);
  int srcy = (int)((relativeY / (float)dest.height) * cut.height);
  int srcw = (int)((destw / (float)dest.width) * cut.width);
  int srch = (int)((desth / (float)dest.height) * cut.height);
  SDL_Rect src = {cut.x + srcx, cut.y + srcy, srcw, srch};

  image.draw(imageId, src, dest.x + relativeX, dest.y + relativeY, destw, desth,
             angle);
}
